//
//  YYFillInformationVC.m
//  drivingSchool
//
//  Created by 子yu 刘 on 2018/8/11.
//  Copyright © 2018年 子yu 刘. All rights reserved.
//

#import "YYFillInformationVC.h"
#import "YYChooseTeacherVC.h"
#import "YYInvoiceVC.h"
#import "YYPayVC.h"

@interface YYFillInformationVC ()
@property (nonatomic ,copy)NSString * teacherId;
@property (nonatomic ,copy)NSString * is_invoice;
@property (nonatomic ,copy)NSString * type;
@property (nonatomic ,copy)NSString * invoice_name;
@property (nonatomic ,copy)NSString * invoice_number;

@end

@implementation YYFillInformationVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.is_invoice = @"0";
    _invoice_name = @"0";
    _invoice_number = @"0";
    _type = @"0";
    _teacherId = @"0";
    [self getData];
}

- (void)getData{
    [RequestOperationManager studentEntry_schoolId:self.schoolId success:^(id result) {
        if (DEF_REQ_SUCCESS) {
            NSDictionary * student = result[@"data"][@"student"];
            if ([student isKindOfClass:[NSDictionary class]]) {
                self.tfName.text = student[@"name"];
                self.tfPhone.text = student[@"iphone"];
                self.tfCardNo.text = student[@"idnumber"];
            }
        }
        
    } failture:^(NSError *error) {
        
    }];
}

- (IBAction)chooseBill:(id)sender {
    YYInvoiceVC * invoice = (YYInvoiceVC *)[CFUtility getVC:@"YYInvoiceVC" Storyboard:HOME];
    MJWeakSelf;
    invoice.block = ^(NSString *type, NSString *title, NSString *name) {
        weakSelf.invoice_name = name;
        weakSelf.invoice_number = title;
        if ([type isEqualToString:@"0"]) {
            weakSelf.lbBill.text = @"无需发票";
           weakSelf.is_invoice = @"0";
            weakSelf.type = @"0";
        }else if ([type isEqualToString:@"1"]) {
            weakSelf.lbBill.text = @"个人发票";
            weakSelf.is_invoice = @"1";
             weakSelf.type = @"1";
        }else if ([type isEqualToString:@"2"]) {
            weakSelf.is_invoice = @"1";
            weakSelf.lbBill.text = @"公司发票";
             weakSelf.type = @"2";
        }
       
    };
    [self.navigationController pushViewController:invoice animated:YES];
}
- (IBAction)chooseTeacher:(id)sender {
    YYChooseTeacherVC * teacherVc = (YYChooseTeacherVC *)[CFUtility getVC:@"YYChooseTeacherVC" Storyboard:HOME];
    teacherVc.schoolId = _schoolId;
    MJWeakSelf;
    teacherVc.block = ^(NSDictionary *teacher) {
        if (teacher) {
             weakSelf.lbTeacher.text = teacher[@"teacher_name"];
            weakSelf.teacherId = teacher[@"id"];
        }else{
             weakSelf.teacherId = @"0";
             weakSelf.lbTeacher.text = @"无";
        }
       
    };
    [self.navigationController pushViewController:teacherVc animated:YES];
    
}
- (IBAction)submit:(id)sender {
    if (self.tfName.text.length == 0) {
        [AlertUtil alertMessage:@"请输入您的姓名"];
        return;
    }
    if (self.tfCardNo.text.length == 0) {
        [AlertUtil alertMessage:@"请输入身份证号码"];
        return;
    }
    if (![RegularValidateUtils validateIdentityCard:self.tfCardNo.text]) {
        [AlertUtil alertMessage:@"身份证号码格式不对"];
        return;
    }
    if (self.tfPhone.text.length!=11) {
        [AlertUtil alertMessage:@"请输入正确的手机号码"];
        return;
    }
 
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:_schoolId forKey:@"school_id"];
     [dict setObject:_tfName.text forKey:@"name"];
     [dict setObject:_tfPhone.text forKey:@"iphone"];
     [dict setObject:_tfCardNo.text forKey:@"idnumber"];
    [dict setObject:_price_id forKey:@"price_id"];
    [dict setObject:_teacherId forKey:@"teacher_id"];
    [dict setObject:_is_invoice forKey:@"is_invoice"];
    [dict setObject:_type forKey:@"type"];
    [dict setObject:self.invoice_number forKey:@"invoice_number"];
    [dict setObject:self.invoice_name forKey:@"invoice_name"];
    [dict setObject:@"iOS" forKey:@"source"];
    YYPayVC * pay = (YYPayVC *)[CFUtility getVC:@"YYPayVC" Storyboard:HOME];
    pay.isHidden = NO;
    pay.money = @"100";
    pay.parme = dict;
    
    pay.payBlock = ^(NSString *type) {
        if ([type isEqualToString:@"0"]) {
            [RequestOperationManager studyCar_parm:dict _success:^(id result) {
                if (DEF_REQ_SUCCESS) {
                    [self aliPayWithSign:result[@"data"]];
                }
            } failture:^(NSError *error) {
                
            }];
        }else{
            [RequestOperationManager studyCarWxpay_parm:dict _success:^(id result) {
                if (DEF_REQ_SUCCESS) {
                    [self wechatPayWithResponse:result[@"data"]];
                }
                
            } failture:^(NSError *error) {
                
            }];
        }

    };
    [self.navigationController pushViewController:pay animated:YES];

}

- (void)wechatPayWithResponse:(NSDictionary *)response {
    PayReq* req  = [[PayReq alloc] init];
    req.partnerId = response[@"partnerid"];
    req.prepayId= response[@"prepayid"];
    req.package = response[@"package"];
    req.nonceStr= response[@"noncestr"];
    req.timeStamp= [response[@"timestamp"] intValue];
    req.sign=response[@"sign"];
  // __weak typeof(self) weakSelf = self;
    
    [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        if (errCode == FLErrCodeSuccess) {
             YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
        }
    }];
}

- (void)aliPayWithSign:(NSString * )sign{
    /**
     *  @author gitKong
     *
     *  来自支付宝文档数据
     */
    [FLPAYMANAGER fl_payWithOrderMessage:sign callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
        if (resultDic&&[resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            YYHintVC * hint = (YYHintVC *)[CFUtility getVC:@"YYHintVC" Storyboard:INSURANCE];
            NSDictionary * data = @{@"title":@"支付成功",
                                    @"image":@"sign_success",
                                    @"content":@"客服稍后会联系您，请保持电话畅通谢谢"
                                    };
            hint.viewDict = data;
            [self.navigationController pushViewController:hint animated:YES];
        }else{
            [AlertUtil alertMessage:errStr];
        }
    }];
}

- (NSString *)jumpToBizPay {
    //============================================================
    /**
     *  @author Clarence
     *
     *  来自微信文档数据
     */
    //============================================================
    NSString *urlString   = @"http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios";
    //解析服务端返回json数据
    NSError *error;
    //加载一个NSURL对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    //将请求的url数据放到NSData对象中
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if ( response != nil) {
        NSMutableDictionary *dict = NULL;
        //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
        dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        NSLog(@"url:%@",urlString);
        if(dict != nil){
            NSMutableString *retcode = [dict objectForKey:@"retcode"];
            if (retcode.intValue == 0){
                NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.partnerId           = [dict objectForKey:@"partnerid"];
                req.prepayId            = [dict objectForKey:@"prepayid"];
                req.nonceStr            = [dict objectForKey:@"noncestr"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dict objectForKey:@"package"];
                req.sign                = [dict objectForKey:@"sign"];
                
                [FLPAYMANAGER fl_payWithOrderMessage:req callBack:^(FLErrCode errCode, NSString *errStr, NSDictionary *resultDic) {
                    NSLog(@"errCode = %zd,errStr = %@",errCode,errStr);
                }];
                //日志输出
                NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",[dict objectForKey:@"appid"],req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
                return @"";
            }else{
                return [dict objectForKey:@"retmsg"];
            }
        }else{
            return @"服务器返回错误，未获取到json对象";
        }
    }else{
        return @"服务器返回错误";
    }
    
}



@end
